package function;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import boot.Boot;
import files.Files;

public class NavigatorSaver {

	public static final String FILE_PATH = Files.BOOT_ROOT
			+ "/Navigator/Navigator.db";
	private ChainMp3 firstNode;
	private OutputStream fos;

	public NavigatorSaver(ChainMp3 theFirstNode) {
		firstNode = theFirstNode;
	}

	public void save() {
		save(FILE_PATH);
	}

	private void save(String aFilePath) {
		if (firstNode == null) {
			return;
		}
		try {
			FileConnection fc = (FileConnection) Connector.open(aFilePath);
			if (fc.exists()) {
				fc.delete();
			}
			fc.create();

			fos = fc.openOutputStream();
			writeRecords();
			fos.close();

			fc.close();
		} catch (IOException e) {
			Boot.alertException(e, this, "save()");
		}
	}

	private void writeRecords() {
		try {
			ChainMp3 current = firstNode;

			while (current != null) {
				Mp3File mp3File = current.getMp3File();
				fos.write(((mp3File.getFilePath() + "\r\n").getBytes()));
				current = current.getNext();
			}

		} catch (IOException e) {
			Boot.alertException(e, this, "writeRecords()");
		}
	}

	public void savePlaylist(String name) {
		if (firstNode == null) {
			return;
		}
		makePlaylistFolder();
		String path = Files.PLAYLIST_PATH + "/" + name + ".pdb";
		save(path);
	}

	private void makePlaylistFolder() {
		try {
			FileConnection dirFc = (FileConnection) Connector
					.open(Files.PLAYLIST_PATH);
			if (!dirFc.exists()) {
				dirFc.mkdir();
			}
			dirFc.close();
		} catch (IOException e) {
			Boot.alertException(e, this, "malePlaylistFolder()");
		}
	}
}
